import React, { useRef, useEffect } from 'react';
import { jsapi, viewUtils } from '@/utils/arcgis';
import { drawPoint } from './drawFn';

/**
 *
 * @param {object} layerCfg graphic layer
 * @param {function} getView 返回view的函数
 * @returns
 */
function useDrawPoint(layerCfg = {}, getView = void 0) {
  const GraphicRef = useRef(null);
  const layerRef = useRef(null);
  const viewRef = useRef(null);

  useEffect(() => {
    init();
    return () => {};
  }, []);

  async function init() {
    const [GraphicsLayer, Graphic] = await jsapi.load([
      'esri/layers/GraphicsLayer',
      'esri/Graphic',
    ]);

    GraphicRef.current = Graphic;
    viewRef.current = await viewUtils.isViewReady(getView);

    // 复用已挂载layer
    if (layerCfg.id) {
      layerRef.current = viewRef.current.map && viewRef.current.map.findLayerById(layerCfg.id);
    }

    if (!layerRef.current) {
      layerRef.current = new GraphicsLayer({
        elevationInfo: {
          mode: 'relative-to-scene',
        },
        ...layerCfg,
      });
    }

    // 用于比对
    updatePointGraphic.layer = layerRef.current;

    viewRef.current.map.add(layerRef.current);
  }

  function createPointGraphic(symbol) {
    // if ( !GraphicRef.current) {
    //   console.error('graphic初始化失败')
    //   return Promise.reject()
    // }
    const graphic = new GraphicRef.current({ symbol });
    return drawPoint({ graphic, layer: layerRef.current, view: viewRef.current }).then(() => {
      return graphic;
    });
  }

  function updatePointGraphic(graphic) {
    console.log('update point');
    if (graphic.geometry.type === 'point') {
      return drawPoint(
        { graphic, layer: layerRef.current, view: viewRef.current },
        false,
      ).then(() => [graphic]);
    } else {
      throw new Error('必须更新点graphic');
    }
  }

  return [createPointGraphic, updatePointGraphic];
}

export default useDrawPoint;
